#pragma once
#include "Protocol.hpp"

enum {
    Div_Zero = 1,
    Mod_Zero,
    Other_Err,
};

class SvrCal
{
public:
    SvrCal() {}
    ~SvrCal() {}

    // 计算text中的数据，出错返回空字符串
    string doCalculate(string& text)
    {
        // 将从网络上来的数据，去掉报头
        string out;
        bool r = decode(text, &out);
        if(r == false)  {
            // cerr << "decode() error" << endl;
            return "";
        }
        // printf("Now out: %s\n", out.c_str());
        // 反序列化
        Request req;
        r = req.deserialize(out);
        if(r == false)  {
            cerr << "deserialize() error" << endl;
            return "";
        }

        // 计算结果
        Response resp = calHelper(req);

        // 序列化
        out = "";
        resp.serialize(&out);

        // 将计算结果加上报头
        out = encode(out);

        return out;
    }
private:
    Response calHelper(Request& req)
    {   
        // 将Request转换为Response
        Response resp;
        switch (req._op)
        {
        case '+':
            resp._res = req._a + req._b;
            break;
        case '-':
            resp._res = req._a - req._b;
            break;
        case '*':   
            resp._res = req._a * req._b;
            break;
        case '/':
        {
            if(req._b == 0)  
                resp._exitCode = Div_Zero;
            else 
                resp._res = req._a / req._b;
        }
        break;
        case '%':
        {
            if(req._b == 0)  
                resp._exitCode = Mod_Zero;
            else 
                resp._res = req._a % req._b;
        }
        break;
        default:
            resp._exitCode = Other_Err;
            break;
        }
        return resp;
    }
};